package com.aitou.mrylive.presentation.ui.main.index;

import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.magiepooh.recycleritemdecoration.ItemDecorations;
import com.jakewharton.rxbinding.view.RxView;
import com.aitou.mrylive.R;
import com.aitou.mrylive.data.bean.AnchorSummary;
import com.aitou.mrylive.data.bean.HotAnchorSummary;
import com.aitou.mrylive.data.bean.ThemBean;
import com.aitou.mrylive.data.repository.SourceFactory;
import com.aitou.mrylive.domain.LocalDataManager;
import com.aitou.mrylive.presentation.ui.base.BaseFragment;
import com.aitou.mrylive.presentation.ui.base.ptr.BasePtr;
import com.aitou.mrylive.presentation.ui.base.recycler.SimpleRecyclerAdapter;
import com.aitou.mrylive.presentation.ui.base.recycler.SimpleRecyclerHolder;
import com.aitou.mrylive.presentation.ui.main.me.OtherUserActivity;
import com.aitou.mrylive.presentation.ui.main.topic.AllTopicActivity;
import com.aitou.mrylive.presentation.ui.main.topic.NewsTopicActivity;
import com.aitou.mrylive.presentation.ui.room.RoomActivity;
import com.aitou.mrylive.presentation.ui.room.player.PlayerFragment;
import com.aitou.mrylive.util.Const;
import com.aitou.mrylive.util.PicUtil;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.zip.Inflater;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import rx.functions.Action1;

/**
 * 推荐
 * @author Muyangmin
 * @since 1.0.0
 */
public class RecommendAnchorFragment extends BaseFragment implements RecommendInterface {

    private RecommendPresenter presenter;

    //    话题的那个
    public static final int TYPE_HEADER = 0;
    //    普通的type
    public static final int TYPE_NORMAL = 1;
    private PtrFrameLayout ptrFrameLayout;
    private RecyclerView recyclerView;
    private View viewEmpty;
    private RecommendAdapter adapter;
    private View mThemlayout;
    private TagFlowLayout mFlowLayout;
    //    话题的对象集合
    private List<ThemBean.Topic> list;
    //    话题的字符串集合
    private List<String> tipoclist;
//    跳转到热门
    private TextView goHot;
//    跳转到人呢的回调
    private RecommendShowHot recommendShowHot;
    public static RecommendAnchorFragment newInstance() {
        return new RecommendAnchorFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_recommend_anchor;
    }

    @Override
    protected void initViews(View view) {
        mThemlayout=getActivity().getLayoutInflater().inflate(R.layout.recommend_them_tagflow_layout,null);
        mFlowLayout= (TagFlowLayout) mThemlayout.findViewById(R.id.id_flowlayout);

        presenter = new RecommendPresenter(this);
        ptrFrameLayout = $(view, R.id.recommend_anchor_ptr);
        viewEmpty = $(view, R.id.recommend_tv_empty);
        BasePtr.setRefreshOnlyStyle(ptrFrameLayout);
        goHot=$(view,R.id.followed_anchor_tv_view_hot);
        goHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recommendShowHot.showHot();
            }
        });
        recyclerView = $(view, R.id.recommend_anchor_recycler);
        recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(),3));
        recyclerView.addItemDecoration(ItemDecorations.vertical(view.getContext())
                .type(0, R.drawable.divider_decoration_transparent_h1)
                .create());

        ptrFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, recyclerView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.loadRecommendAnchors(LocalDataManager.getInstance().getLoginInfo().getToken());
                presenter.getThemBean("8");
            }
        });
        presenter.getThemBean("8");
        ptrFrameLayout.autoRefresh();

    }

    public interface RecommendShowHot{
        void showHot();
    }

    public void setRecommendShowHot(RecommendShowHot recommendShowHot) {
        this.recommendShowHot = recommendShowHot;
    }

    @Override
    public void showData(List<AnchorSummary> list) {
        viewEmpty.setVisibility(View.INVISIBLE);
        if (adapter == null) {
            adapter = new RecommendAdapter(list);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setDataList(list);
        }
    }

    @Override
    public void onResume() {
//        MobclickAgent.onPageStart("主页-最新");
        super.onResume();
    }

    @Override
    public void onPause() {
//        MobclickAgent.onPageStart("主页-最新");
        super.onPause();
    }

    @Override
    public void appendData(List<AnchorSummary> list) {
        adapter.appendData(list);

    }

    @Override
    public void showEmptyResult() {
        //Clear data
        if (adapter != null) {
            adapter.setDataList(new ArrayList<AnchorSummary>());
        }
        viewEmpty.setVisibility(View.VISIBLE);
    }

    @Override
    public void onThemBean(ThemBean themBean) {
        viewEmpty.setVisibility(View.INVISIBLE);
        if (themBean != null) {
            tipoclist = new ArrayList<>();
            list = themBean.getTopic();
        }
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                tipoclist.add(list.get(i).getTopic_title());
            }
            tipoclist.add(getString(R.string.recommend_host_topic));

            mFlowLayout.setAdapter(new TagAdapter(tipoclist) {
                @Override
                public View getView(FlowLayout parent, int position, Object o) {
                    TextView tv = (TextView) getActivity().getLayoutInflater().inflate(R.layout.recommend_them_item,
                            mFlowLayout, false);
                    tv.setText("# "+tipoclist.get(position)+" #");
                    if (position==tipoclist.size()-1){
                        tv.setText(tipoclist.get(position));
                        tv.setTextColor(0xffffffff);
                        tv.setBackgroundResource(R.drawable.recommend_them_flow_hot_bg);
                    }
                    return tv;
                }
            });
            mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
            {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent)
                {
                    if (tipoclist.get(position).equals(getString(R.string.recommend_host_topic))){
//                        如果是热门话题则跳转到所有热门
                        startActivity(AllTopicActivity.createIntent(getActivity()));
                        return true;
                    }
                    startActivity(NewsTopicActivity.createIntent(getActivity(),list.get(position).getTopic_id(),list.get(position).getTopic_title()));
                    return true;
                }
            });
        }
    }

    @Override
    public void showLoadingComplete() {
        super.showLoadingComplete();
        ptrFrameLayout.refreshComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.unsubscribeTasks();
    }

    private class RecommendAdapter extends SimpleRecyclerAdapter<AnchorSummary,
            RecommendHolder> {


        public RecommendAdapter(List<AnchorSummary> anchorSummaries) {
            super(anchorSummaries);
        }

        @Override
        protected int getItemLayoutId(int viewType) {
            return R.layout.item_recommend_user_result;
        }

        @NonNull
        @Override
        protected RecommendHolder createHolder(View view) {
            return new RecommendHolder(view);
        }


        @Override
        public void onBindViewHolder(RecommendHolder holder, int position) {
            if(getItemViewType(position) == TYPE_HEADER) return;
            super.onBindViewHolder(holder, getRealPosition(holder));
        }

        public int getRealPosition(RecyclerView.ViewHolder holder) {
            int position = holder.getLayoutPosition();
            if (mThemlayout!=null){
                return position-1;
            }
            return position;
        }

        //    总的item个数
        @Override
        public int getItemCount() {
            if (mThemlayout!=null){
                return getDataList().size()+1;
            }
            return getDataList().size();
        }

        //    返回不用的viewtype 的id
        @Override
        public int getItemViewType(int position) {
            if (mThemlayout!=null&&position==0){
                return  TYPE_HEADER;
            }else {
                return TYPE_NORMAL;
            }
        }
        //  创建viewholder
        @Override
        public RecommendHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //        如果头头不为空，并且样式是头头，那么就返回一个头头
            if(mThemlayout != null && viewType == TYPE_HEADER){ return new RecommendHolder(mThemlayout);}
            return super.onCreateViewHolder(parent, viewType);
        }

        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            if(manager instanceof GridLayoutManager) {
                final GridLayoutManager gridManager = ((GridLayoutManager) manager);
                gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return getItemViewType(position) == TYPE_HEADER
                                ? gridManager.getSpanCount() : 1;
                    }
                });
            }
        }
    }

    private class RecommendHolder extends SimpleRecyclerHolder<AnchorSummary> {

        private TextView tvCity;
        private SimpleDraweeView draweeAvatar;
        private ImageView  imgLevel, imgStar;


        public RecommendHolder(View itemView) {
            super(itemView);
            if (itemView==mThemlayout){
                return;
            }
            tvCity = (TextView) itemView.findViewById(R.id.item_search_anchor_tv_city);
//            tvIntro = (TextView) itemView.findViewById(R.id.item_search_anchor_tv_intro);
            draweeAvatar = (SimpleDraweeView) itemView.findViewById(R.id.img_user_avatar);
//            imgGender = (ImageView) itemView.findViewById(R.id.item_search_anchor_img_gender);
            imgLevel = (ImageView) itemView.findViewById(R.id.item_search_anchor_img_level);
            imgStar = (ImageView) itemView.findViewById(R.id.img_user_star_type);
//            imgbtnFollow = (ImageButton) itemView.findViewById(R.id.item_search_anchor_imgbtn_follow);
        }

        @Override
        public void displayData(final AnchorSummary data) {
//            imgbtnFollow.setVisibility(View.GONE);

            tvCity.setText("火星");
//            tvIntro.setText(data.getIntro());
            if (!TextUtils.isEmpty(data.getAvatar())) {
                draweeAvatar.setImageURI(SourceFactory.wrapPathToUri(data.getAvatar()));
            }
//            imgGender.setImageResource(SourceFactory.isMale(data.getSex()) ?
//                    R.drawable.ic_global_male : R.drawable.ic_global_female);
            imgLevel.setImageResource(PicUtil.getLevelImageId(itemView.getContext(), data.getEmceeLevel()));
//            RxView.clicks(imgbtnFollow)
//                    .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
//                    .subscribe(
//                            new Action1<Void>() {
//                        @Override
//                        public void call(Void aVoid) {
//                            if (data.isFollowing()) {
//                                data.setFollowing(false);
//                                imgbtnFollow.setImageResource(R.drawable.ic_follow);
//                                presenter.unfollowAnchor(data.getId());
//                            } else {
//                                data.setFollowing(true);
//                                imgbtnFollow.setImageResource(R.drawable.ic_followed);
//                                presenter.followAnchor(data.getId());
//                            }
//                        }
//                    });
            RxView.clicks(itemView)
                    .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
//                            startActivity(OtherUserActivity.createIntent(getActivity(),
//                                    Integer.parseInt(data.getId()),true));

                            HotAnchorSummary hotAnchorSummary=new HotAnchorSummary();
                            hotAnchorSummary.setSnap(data.getSnap());
                            hotAnchorSummary.setOnlineCount(0);
                            hotAnchorSummary.setAvatar(data.getAvatar());
                            hotAnchorSummary.setCity(data.getCity());
                            hotAnchorSummary.setCurrentRoomNum(data.getCurrentRoomNum());
                            hotAnchorSummary.setId(data.getId());
                            hotAnchorSummary.setNickname(data.getNickname());
                            startActivity(RoomActivity.createIntent(getActivity(),
                                    RoomActivity.TYPE_VIEW_LIVE,
                                    data.getCurrentRoomNum(),
                                    data.getId(),
                                    PlayerFragment.createArgs(hotAnchorSummary)));
                            getActivity().overridePendingTransition(R.anim.fragment_slide_left_in, R.anim
                                    .fragment_slide_left_out);
                        }
                    });

//            imgStar.setImageResource(R.drawable.global_star_1);
        }
    }
}
